#include "MyHTTPClient.h"

using namespace boost::asio;

MyHTTPClient::MyHTTPClient()
{
    this->connected = false;
    this->socket = new boost::asio::ip::tcp::socket(this->io_service);
}

MyHTTPClient::~MyHTTPClient()
{
    this->disconnect();
    delete this->socket;
}

void            MyHTTPClient::connect()
{
    this->disconnect();
    ip::tcp::resolver resolver(io_service);
    ip::tcp::resolver::query query(address, "http");
    ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
    ip::tcp::resolver::iterator end;
    boost::system::error_code error = boost::asio::error::host_not_found;
    while (error && endpoint_iterator != end)
    {
        this->socket->close();
        this->socket->connect(*endpoint_iterator++, error);
    }
    if (error)
        throw boost::system::system_error(error);
    this->connected = true;
}

const void      MyHTTPClient::disconnect()
{
    if (this->connected)
    {
        this->socket->close();
        this->connected = false;
    }
}

const bool      MyHTTPClient::isConnected() const
{
    return this->connected;
}

void            MyHTTPClient::createHeader(const std::string file)
{
    this->address = file;
    this->file = file;
    if (this->address.compare(0, 7, "http://") == 0)
    {
        this->address = this->address.substr(7, this->address.find("/", 7) - 7);
        this->file = this->file.substr(this->file.find("/", 7), this->file.size());
    }
    this->header = "GET " + this->file;
    this->header += "\nHost: " + this->address;
    this->header += "\nFrom: KreogRSS\n";
}

void     MyHTTPClient::sendRequest(const std::string url)
{
    this->disconnect();
    this->createHeader(url);
    this->connect();
    boost::system::error_code ignored_error;
    boost::asio::write(*this->socket, boost::asio::buffer(this->header), boost::asio::transfer_all(), ignored_error);
}

std::string*     MyHTTPClient::recvRss()
{
    std::string *file = new std::string();
    if (this->connected)
    {
        size_t len;
        do
        {
            boost::array<char, 1024> buf;
            boost::system::error_code error;
            len = this->socket->read_some(boost::asio::buffer(buf), error);
            file->append(buf.c_array(), len);
        }
        while (len != 0 && !(file->size() > 8 && file->compare(file->size() - 8, 6, "</rss>") == 0));
        if (file->find("\nLocation: ") != std::string::npos)
        {
            this->address = file->substr(file->find("\nLocation: ") + 11, file->find("\n", file->find("\nLocation: ") + 11) - (file->find("\nLocation: ") + 11));
            this->sendRequest(this->address);
            return this->recvRss();
        }
    }
    return file;
}
